import React, { useState, useEffect } from 'react';
import { TjContent, TjFilter, TjHeader } from '@/tjComponents';
import TjTable from '@/pages/ETrade/components/TjTable';
import { getColumns } from './helper';
import { Button, Drawer, message, Modal, Pagination, Select, Spin } from 'antd';
import { callChromeFn, callChromeBefore, logoutAfter } from './quickLogin';
import { HttpCode } from '#/utils/contacts.js';
import {
  addAccountInfo,
  delAccountInfo,
  editAccountInfo,
  exportListData,
  getUserNameList,
  loginOut,
  pageAccountInfo,
  queryCookies,
} from './service';
import { ExclamationCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import InstallModal from './components/InstallModal';
import DrawerContent from './components/DrawerContent';
import { useSetState } from 'ahooks';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { connect } from 'umi';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProgressProps } from 'antd';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import type { Store } from 'antd/lib/form/interface';
import { LoadingOutlined } from '@ant-design/icons';
import { downloadFileForFront } from '@/tjComponents/TjUpload/TjUploadContent';
import { useForm } from 'antd/lib/form/Form';
import _ from 'lodash';
import moment from 'moment';
import './index.less';

const { confirm } = Modal;

const OneClickLogin: React.FC<IOneClickLoginProps> = (props) => {
  const hasPermission = (code: string) => {
    return !(props.buttonPermissions || []).some(
      (item: { menuCode: string }) => item.menuCode === code,
    );
  };
  const hasDel = hasPermission('OneClickLoginDetele');
  const hasEdit = hasPermission('OneClickLoginEdit');

  const [form] = useForm();
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<ProvinceType>();
  const [userNames, setUserNames] = useState<any[]>([]);
  const [defaultValues, setDefaultValues] = useState<any>();
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      const obj = {
        stationIds: parmas.stations.map((v: StationType) => {
          return v.stationId;
        }),
        marketId: parmas.value,
        userNameList: undefined,
      };
      setCurrentProvinceInfo(parmas);
      setDefaultValues(obj);
      setReq(obj);
      getUserList(obj.stationIds);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [loading, setLoading] = useState<boolean>(false);
  const [req, setReq] = useSetState<any>({
    pageSize: 10,
    currentPage: 1,
  });
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [pagination, setPagination] = useSetState<any>({
    pageSize: 0,
    total: 0,
    currentPage: 1,
  });
  const [installVisible, setInstallVisible] = useState<boolean>(false);
  const [loginLoading, setLoginLoading] = useState<boolean>(false);

  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [editValues, setEditValues] = useState<any>(null);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [spinType, setSpinType] = useState<string>('login');
  const [formIsChange, setFormIsChange] = useState<boolean>(false);

  const loginJudge = (row: any) => {
    login(row);
  };

  const login = (row: any) => {
    callChromeBefore()
      .then((pluginInfo) => {
        const { extensionId } = pluginInfo;
        const dataId = row.dataId;
        setSpinType('login');
        setLoginLoading(true);
        queryCookies(dataId)
          .then((res: any) => {
            if (res.statusCode === HttpCode.SUCCESS && res.data && res.data.cookies) {
              callChromeFn(extensionId, {
                type: 'quickLogin',
                ...res.data,
                url: res.data.baseUrl,
                dataId: dataId,
              }).then((res: any) => {
                setTimeout(() => {
                  setReq({
                    refreshTime: moment().valueOf(),
                  });
                }, 10);
              });
            } else {
              message.error(res.message);
            }
          })
          .finally(() => {
            setLoginLoading(false);
          });
      })
      .catch((err) => {
        if (!err) {
          notInstallPlugin();
        }
      });
  };

  const logout = (row: any, flag?: boolean) => {
    setSpinType('logout');
    setLoginLoading(true);
    loginOut({ dataId: row.dataId, confirm: flag ? flag : false })
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success('登出成功');
          setReq({
            refreshTime: moment().valueOf(),
          });
          closeCurrentBrowserTab(row);
        } else if (res.statusCode === '1002') {
          confirm({
            title: res.message,
            icon: <ExclamationCircleOutlined />,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              logout(row, true);
            },
          });
        } else {
          message.warning(res.message);
        }
      })
      .finally(() => {
        setLoginLoading(false);
      });
  };

  const closeCurrentBrowserTab = (row: any) => {
    logoutAfter(row.dataId);
  };

  const notInstallPlugin = () => {
    setInstallVisible(true);
  };

  const add = () => {
    setEditValues(null);
    setDrawerVisible(true);
  };

  const exportList = () => {
    const params = {
      ...req,
    };
    if (params.userNameList) {
      params.userNameList = [params.userNameList];
    }
    delete params.refreshTime;
    exportListData({
      marketId: req.marketId,
      stationIds: req.stationIds,
      userNameList: req.userNameList ? [req.userNameList] : [],
    }).then((res: any) => {
      if (res) {
        downloadFileForFront(res, `账号信息.xlsx`);
      }
    });
  };

  const onClose = (judge?: boolean) => {
    if (formIsChange && judge) {
      confirm({
        title: '信息未保存，是否确认关闭？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          setDrawerVisible(false);
          setEditValues(undefined);
          setFormIsChange(false);
        },
      });
    } else {
      setDrawerVisible(false);
      setEditValues(undefined);
      setFormIsChange(false);
    }
  };

  const changePagination = (page: number, size?: number) => {
    setReq({
      currentPage: page,
      pageSize: size,
    });
  };

  const onSearch = (value: any) => {
    setReq({ ...value, refreshTime: moment().valueOf(), currentPage: 1 });
  };

  const onReset = (value: any) => {
    getUserList(value.stationIds);
    setReq({ ...value, refreshTime: moment().valueOf(), currentPage: 1 });
    const item = _.find(province, (n: ProvinceType) => n.value === value.marketId);
    if (item) {
      setCurrentProvinceInfo(item);
    }
  };

  const query = () => {
    setLoading(true);
    const params = {
      ...req,
    };
    if (params.userNameList) {
      params.userNameList = [params.userNameList];
    }
    delete params.refreshTime;

    pageAccountInfo(params)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const { size, total, current } = res.data;
          const { records } = res.data;

          const newList = records.map((item: any) => {
            const currentMarket = _.find(
              item.marketList,
              (n: any) => n.value && n.value === item.dataId,
            );
            return {
              ...item,
              loginStatus: currentMarket ? currentMarket.loginStatus : '',
              crawlerStatus: currentMarket ? currentMarket.crawlerStatus : '',
              loginUser: currentMarket ? currentMarket.loginUser : '',
            };
          });
          setDataSource(newList || []);

          setPagination({
            pageSize: size,
            total,
            currentPage: current,
          });
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      const stationIds = item.stations.map((v: StationType) => {
        return v.stationId;
      });
      form.setFieldsValue({
        stationIds,
        userNameList: undefined,
      });
      getUserList(stationIds);
    }
  };

  const changeStationIds = (val: string[]) => {
    form.setFieldsValue({
      userNameList: undefined,
    });
    getUserList(val);
  };

  const edit = (row: any) => {
    setEditValues(row);
    setDrawerVisible(true);
  };

  const del = (row: any) => {
    confirm({
      title: '确定删除此行数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        delAccountInfo(row.id)
          .then((res: any) => {
            if (res && res.statusCode === HttpCode.SUCCESS) {
              message.success('删除成功');
              setReq({
                refreshTime: moment().valueOf(),
                currentPage: 1,
              });
            } else {
              message.error(res.message);
            }
          })
          .catch(() => {
            setLoading(false);
          });
      },
    });
  };

  const submitData = (data: Store) => {
    let fn = () => addAccountInfo(data);
    if (editValues) {
      fn = () => editAccountInfo(data);
    }
    setBtnLoading(true);
    fn()
      .then((res: any) => {
        if (res) {
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.success(editValues ? '修改成功' : '新增成功');
            if (req.stationIds && req.stationIds.length > 0) {
              form.setFieldsValue({
                userNameList: undefined,
              });
              getUserList(req.stationIds);
            }
            onClose(false);

            setReq({
              refreshTime: moment().valueOf(),
              userNameList: undefined,
            });
          } else {
            if (res.data) {
              const str = res.data.join(',') || '';
              message.error(editValues ? `修改失败:${str}` : `新增失败:${str}`);
            } else {
              message.error(editValues ? `修改失败` : `新增失败`);
            }
          }
        } else {
          message.error('系统异常');
        }
      })
      .finally(() => {
        setBtnLoading(false);
      });
  };

  const getUserList = (arr: string[]) => {
    getUserNameList(arr).then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        setUserNames(res.data);
      }
    });
  };

  const tableChangeMarket = (val: number, index: number) => {
    const newList = [...dataSource];
    newList[index].dataId = val;
    const marketList = newList[index].marketList;
    if (marketList) {
      const item = _.find(marketList, (n: any) => n.value && n.value === val);
      if (item) {
        newList[index].loginStatus = item ? item.loginStatus : '';
        newList[index].crawlerStatus = item ? item.crawlerStatus : '';
        newList[index].loginUser = item ? item.loginUser : '';
      }
    }
    setDataSource(newList);
  };

  useEffect(() => {
    if (req.marketId && req.stationIds) {
      query();
    }
  }, [req]);

  return (
    <Spin
      indicator={<LoadingOutlined style={{ fontSize: 60 }} spin />}
      spinning={loginLoading}
      tip={spinType === 'login' ? '正在努力登录中，请稍后...' : '正在登出，请稍后...'}
      className="quick-login-spin"
    >
      <div className="one-click-login">
        <TjHeader
          left={
            <TjFilter
              form={form}
              defaultValues={defaultValues}
              items={[
                {
                  name: 'marketId',
                  render: (
                    <Select
                      options={province}
                      style={{ width: 180 }}
                      loading={initLoading}
                      onChange={changeMarketId}
                    />
                  ),
                },
                {
                  name: 'stationIds',
                  render: (
                    <TjMarketingUnit
                      treeData={treeData}
                      marketId={currentProvinceInfo?.value}
                      onChange={changeStationIds}
                    />
                  ),
                },
                {
                  name: 'userNameList',
                  placeholder: '请选择账号',
                  render: (
                    <Select
                      options={userNames}
                      loading={initLoading || loading}
                      style={{ width: 180 }}
                    />
                  ),
                },
              ]}
              loading={loading || initLoading}
              onSearch={onSearch}
              onReset={onReset}
            />
          }
        />
        <TjContent
          titleLeft="一键登录"
          className="content"
          titleRight={
            <>
              <Button
                type="link"
                disabled={hasPermission('OneClickLoginAdd')}
                onClick={add}
                loading={loading || initLoading}
                icon={<PlusCircleOutlined />}
              >
                新建
              </Button>
            </>
          }
        >
          <div className="table-box">
            <TjTable
              columns={getColumns({
                login: loginJudge,
                logout,
                edit,
                del,
                onChangeMarket: tableChangeMarket,
                hasDel,
                hasEdit,
              })}
              dataSource={dataSource}
              isLoading={loading || initLoading}
            />
          </div>
          {dataSource.length > 0 && (
            <div className="pagination-box">
              <Pagination
                onChange={changePagination}
                total={pagination.total}
                pageSize={pagination.pageSize}
                current={pagination.currentPage}
                showSizeChanger
                showQuickJumper
              />
            </div>
          )}
        </TjContent>

        <Modal
          footer={null}
          visible={installVisible}
          closeIcon={false}
          onCancel={() => setInstallVisible(false)}
          destroyOnClose
          maskClosable={false}
        >
          <InstallModal />
        </Modal>

        <Drawer
          title={editValues ? '编辑' : '新增'}
          placement="right"
          onClose={() => onClose(true)}
          visible={drawerVisible}
          width="1164px"
          destroyOnClose
          maskClosable={false}
        >
          <DrawerContent
            submit={submitData}
            values={editValues}
            loading={btnLoading}
            optionsData={{
              province,
            }}
            marketId={req.marketId}
            isEdit={(flag) => setFormIsChange(flag)}
          />
        </Drawer>
      </div>
    </Spin>
  );
};

interface IOneClickLoginProps {
  menuCode: string;
  buttonPermissions: any;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(OneClickLogin);
